﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SDPBC.SiteNavigation.SiteNavTreeView
{
  public partial class SiteNavTreeViewUserControl : UserControl
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        SPUser currentUser = SPContext.Current.Web.CurrentUser;
        List<string> myLinks = new List<string>();
        string sValue;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {          
          // set the SPWebApplication uri
          SPWebApplication webApplication = SPWebApplication.Lookup(new Uri(""));
          SPSiteCollection siteCollections = webApplication.Sites;
          SPWeb rootWeb;

          foreach (SPSite siteCollection in siteCollections)
          {
            try
            {
              rootWeb = siteCollection.OpenWeb();

              if (rootWeb.DoesUserHavePermissions(currentUser.LoginName, SPBasePermissions.ViewPages) == true)
              {
                sValue = string.Format("{0}|{1}", siteCollection.RootWeb.Title, siteCollection.RootWeb.Url);
                myLinks.Add(sValue);
                myLinks.Sort();
              }

              siteCollection.Close();
            }
            catch (Exception ex)
            {
              throw new Exception(ex.Message);
            }
          }
         
          foreach (string site in myLinks)
          {
            string[] splitter = site.Split('|');

            // Create the new node
            TreeNode root = new TreeNode();

            root.Text = splitter[0];
            root.NavigateUrl = splitter[1];
            root.Value = splitter[1];
            root.Target = "_blank";

            // Set the PopulateOnDemand property to true so that the child nodes can be dynamically populated
            root.PopulateOnDemand = true;

            // Set additional properties for the node
            root.SelectAction = TreeNodeSelectAction.Select;

            // Set the nodes to collapsed
            root.CollapseAll();

            tvSiteList.Nodes.Add(root);
          }
        });
      }
    }    

    protected void PopulateSiteCollections(object sender, TreeNodeEventArgs e)
    {
      SPUser currentUser = SPContext.Current.Web.CurrentUser;

      DisplayChildSites(currentUser, e.Node);
    }

    private void DisplayChildSites(SPUser currentUser, TreeNode treeNode)
    {
      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
        string parentUrl = treeNode.Value;

        using (SPWeb oWebsite = new SPSite(parentUrl).OpenWeb())
        {
          SPWebCollection childSites = oWebsite.Webs;

          foreach (SPWeb childSite in childSites)
          {
            TreeNode child = new TreeNode();

            if (childSite.DoesUserHavePermissions(currentUser.LoginName, SPBasePermissions.ViewPages) == true)
            {
              child.Text = childSite.Title;
              child.NavigateUrl = childSite.Url;
              child.Target = "_blank";
              child.Value = childSite.Url;

              // Set the PopulateOnDemand property to true so that the child nodes can be dynamically populated
              child.PopulateOnDemand = true;

              // Set additional properties for the node
              child.SelectAction = TreeNodeSelectAction.Select;

              // Add the new node to the ChildNodes collection of the parent node
              treeNode.ChildNodes.Add(child);
              childSite.Close();
            }
          }
        }
      });
    }    
  }  
}